<template>
  <div class="borrower house">
    <el-card class="box-card" shadow="never" style="border:0px;">
      <el-button
        style="float:right;margin-right:18%;"
        type="primary"
        size="mini"
        v-if="defaultChangeValue!='detail'"
        @click="createHouseDraft(2)"
      >保存草稿</el-button>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        :inline="true"
        label-position="right"
        label-width="110px"
        style="width: 92%; margin-left:30px;"
      >
      <el-collapse v-model="activeNames" accordion class="parentColl">
        <el-collapse-item 
        v-for="(item,index) in dataForm.houseList"
        :key="item.key"
        style="border-bottom: 1px solid #f0f0f0;padding: 10px;" :title="item.title" :name="item.num">
        
        <el-form-item
          label="产证号"
          :prop="'houseList.' + index + '.licenseNo'"
          :rules="{required: true,message: '请输入产证号',trigger: 'blur'}"
        >
          <el-input type="textarea" rows="2" v-model="item.licenseNo" @input="vailInput('licenseNo')"/>
        </el-form-item>
        <el-form-item
          label="持证时间"
          :prop="'houseList.' + index + '.licenseTime'"
          :rules="{required: true,message: '请选择持证日期',trigger: 'change'}"
        >
          <el-date-picker
            v-model="item.licenseTime"
            type="date"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOption"
            placeholder="选择日期"
            style="width:100%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item
          label="房龄"
          :prop="'houseList.' + index + '.houseAge'"
          :rules="{required: true,message: '请输入房龄',trigger: 'blur'}"
        >
          <el-input type="number" v-model="item.houseAge">
            <template slot="append">年</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="获取方式"
          :prop="'houseList.' + index + '.accessType'"
          :rules="{required: true,message: '请输入获取方式',trigger: 'change'}"
        >
          <DicSelect
            dictType="获取方式"
            :dictValue="item.accessType"
            v-on:dictValue="item.accessType = $event"
          />
        </el-form-item>
        <el-form-item
          label="房屋地址"
          :prop="'houseList.' + index + '.areaId'"
          :rules="{required: true,message: '请输入房屋地址',trigger: 'change'}"
        >
          <el-cascader
            v-model="item.regionValues"
            @change="handleChangeRegion(index)"
            :options="regionList"
            clearable
            placeholder="请选择区域"
            :props="{ expandTrigger: 'hover' }"
            style="width:100%;"
          ></el-cascader>
          <!-- <span v-if="showTips" style="font-size:12px;color:red;">{{showMessage}}</span> -->
          <el-alert v-if="item.showTips" :closable="false" type="warning" show-icon>{{item.showMessage}}</el-alert>
        </el-form-item>
        <el-form-item
          label="房产类型"
          :prop="'houseList.' + index + '.estateType'"
          :rules="{ required: true,message: '请选择房产类型',trigger: 'change'}"
        >
          <DicSelect
            dictType="房产类型"
            :dictValue="item.estateType"
            v-on:dictValue="item.estateType = $event"
          />
        </el-form-item>
        <el-form-item
          label="共有情况"
          :prop="'houseList.' + index + '.ownedSituation'"
          :rules="{ required: false,message: '请选择共有情况',trigger: 'change'}"
        >
          <DicSelect
            dictType="共有情况"
            :dictValue="item.ownedSituation"
            v-on:dictValue="item.ownedSituation = $event"
          />
        </el-form-item>
        <el-form-item
          label="房屋详细地址"
          :prop="'houseList.' + index + '.addressDetail'"
          :rules="{required: false,message: '请输入房产详细地址',trigger: 'blur'}"
        >
          <el-input type="textarea" rows="4" v-model="item.addressDetail" />
        </el-form-item>
        <el-form-item
          label="小区名称"
          :prop="'houseList.' + index + '.villageName'"
          :rules="{required: false,message: '请输入小区名称',trigger: 'blur'}"
        >
          <el-input v-model="item.villageName" />
        </el-form-item>
        <el-form-item
          label="楼幢号"
          :prop="'houseList.' + index + '.buildNo'"
          :rules="{required: false,message: '请输入楼幢号',trigger: 'blur'}"
        >
          <el-input v-model="item.buildNo">
            <template slot="append">号</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="不动产单元号"
          :prop="'houseList.' + index + '.unitNumber'"
          :rules="{required: false,message: '请输入不动产单元号',trigger: 'blur'}"
        >
          <el-input v-model="item.unitNumber" @change="handleSeachNumber" />
          <!--这里需要修改成产证号查询 <span v-if="showError" style="font-size:12px;color:red;">该抵押物在系统中有拒件的记录，<a @click="rejectLook">前往查看></a></span> -->
          <el-alert v-if="showError" :closable="false" type="warning" show-icon>
            该抵押物在系统中有拒件的记录，
            <el-link @click="rejectLook" style="margin-top:-3px;" type="danger">前往查看</el-link>
          </el-alert>
        </el-form-item>
        <el-form-item
          label="门牌号"
          :prop="'houseList.' + index + '.doorNo'"
          :rules="{required: false,message: '请输入门牌号',trigger: 'blur'}"
        >
          <el-input v-model="item.doorNo" />
        </el-form-item>
        <el-form-item
          label="抵押物现状"
          :prop="'houseList.' + index + '.currentSituation'"
          :rules="{required: false,message: '请输入抵押物现状',trigger: 'change'}"
        >
          <DicSelect
            dictType="抵押物现状"
            :dictValue="item.currentSituation"
            v-on:dictValue="item.currentSituation = $event"
          />
        </el-form-item>
        <el-form-item
          label="产权人"
          :prop="'houseList.' + index + '.propertyOwner'"
          :rules="{required: false,message: '请输入产权人',trigger: 'blur'}"
        >
          <el-input v-model="item.propertyOwner" />
        </el-form-item>
        <el-form-item
          label="权利(土地)性质"
          :prop="'houseList.' + index + '.landNature'"
          :rules="{ required: false,message: '请选择权利(土地性质',trigger: 'change'}"
        >
          <DicSelect
            dictType="土地权利性质"
            :dictValue="item.landNature"
            v-on:dictValue="item.landNature = $event"
          />
        </el-form-item>
        <el-form-item
          label="权利(房产)性质"
          :prop="'houseList.' + index + '.houseNature'"
          :rules="{ required: false,message: '请输入权利(房产)性质',trigger: 'change'}"
        >
          <el-input v-model="item.houseNature" maxlength="10"/>
        </el-form-item>
        <el-form-item
          label="现使用情况"
          :prop="'houseList.' + index + '.nowUsage'"
          :rules="{ required: false,message: '请选择现使用情况',trigger: 'change'}"
        >
           <DicSelect dictType = "现使用情况" 
           :dictValue="item.nowUsage" 
           v-on:dictValue="item.nowUsage = $event"/>
        </el-form-item>
        <el-form-item
          label="房屋用途"
          :prop="'houseList.' + index + '.houseUse'"
          :rules="{ required: false,message: '请选择房屋用途',trigger: 'change'}"
        >
          <DicSelect
            dictType="房屋用途"
            :dictValue="item.houseUse"
            v-on:dictValue="item.houseUse = $event"
          />
        </el-form-item>
        <el-form-item
          label="土地使用期限"
          :prop="'houseList.' + index + '.durationLandUse'"
          :rules="{required: false,message: '请输入土地使用期限',trigger: 'blur'}"
        >
          <el-input v-model="item.durationLandUse" />
        </el-form-item>
        <el-form-item
          label="建筑面积"
          :prop="'houseList.' + index + '.areaTotal'"
          :rules="{required: false,message: '请输入建筑面积',trigger: 'blur'}"
        >
          <el-input v-model="item.areaTotal">
            <template slot="append">m²</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="楼层数"
          :prop="'houseList.' + index + '.floors'"
          :rules="{required: false,message: '请输入楼层数',trigger: 'blur'}"
        >
          <el-input v-model="item.floors">
            <template slot="append">层</template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="总楼层数"
          :prop="'houseList.' + index + '.floorsTotal'"
          :rules="{required: false,message: '请输入总楼层数',trigger: 'blur'}"
        >
          <el-input v-model="item.floorsTotal">
            <template slot="append">层</template>
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="建筑类型" prop="houseType" :rules="{ required: false,message: '请选择建筑类型',trigger: 'change'}">
          <DicSelect dictType = "住宅类型"  :dictValue="dataForm.houseType" v-on:dictValue="dataForm.houseType = $event"/>
        </el-form-item>-->
        <el-form-item label="房屋朝向"
          :prop="'houseList.' + index + '.buildingHead'"
         >
          <DicSelect
            dictType="房屋朝向"
            :dictValue="item.buildingHead"
            v-on:dictValue="item.buildingHead = $event"
          />
        </el-form-item>
        <el-form-item></el-form-item>

       <div
          v-for="(item1,index1) in item.houseHistries"
          :key="item1.key"
          style="border-bottom: 1px solid #f0f0f0;padding: 10px;"
        >
          <el-form-item
            :label="item1.borrowerTypeName"
            :rules="(pledgeType == 3 && index1 == 0)?borrowRules:null"
          >
            <DicSelect
              dictType="借款机构"
              :dictValue="item1.borrowerOrgType"
              v-on:dictValue="(val) => borrowTypeChange(val,item1)"
            />
            <!-- <el-input v-model="item.borrowerOrg" :placeholder="item.borrowerTypeName" /> -->
          </el-form-item>
          <el-form-item
            label="借款类型"
            :rules="(pledgeType == 3 && index1 == 0)?borrowLoneType:null"
          >
            <DicSelect
              dictType="借款类型"
              :dictValue="item1.loanType"
              v-on:dictValue="(val) => loneTypeChange(val,item1,index1)"
            />
          </el-form-item>
          <el-form-item label="借款金额" >
            <!-- <template slot="append">万</template> -->
            <el-input v-model="item1.money" placeholder="请输入借款金额"></el-input>
          </el-form-item>
          <el-form-item label="期限">
            <el-input type="text" v-model="item1.deadline" placeholder="请输入期限" />
          </el-form-item>
          <el-form-item label="剩余本金">
            <el-input type="number" v-model="item1.remainCapital" placeholder="请输入剩余本金" />
          </el-form-item>
          <el-form-item label="还款方式">
            <el-input v-model="item1.repayWay" autocomplete="off" placeholder="请输入还款方式" />
          </el-form-item>
        </div> 
                <el-form-item style="float:right;" v-if="index>0">
                  <el-button
                  type="danger"
                  size="medium"
                  @click="removeRow(index)"
                >删除</el-button>
                </el-form-item>
        </el-collapse-item>
        
      </el-collapse>

      </el-form>

      <el-form
        :model="formData3"
        ref="formData3"
        status-icon
        label-position="right"
        label-width="120px"
        style="width: 600px; margin-left:50px;"
      >
 

        <el-form-item style="margin-top:30px;">
          <div v-if="defaultChangeValue === 'detail'">
           <el-button  type="primary" @click="addRow" style="width:150px;height:40px;">新增房产</el-button>
            <el-button type="warning" @click="createData" style="width:150px;height:40px;">保存</el-button>
          </div>
          <div v-else>
            
           <el-button  type="primary" @click="addRow" style="width:150px;height:40px;">新增房产</el-button>
            <el-button type="primary" @click="createHouseDraft(1)" style="width:150px;height:40px;" >上一步</el-button>
            <el-button type="warning" @click="createData(2)" style="width:150px;height:40px;">下一步</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style>
</style>

<script>
import { createHouse, createHouseDraft, updateHouse, findByProjectId,deleteHouse } from '@/api/house';
import { listRegion, detailByAreaId } from '@/api/region';
import { findUnitNumber } from '@/api/reject';
import DicSelect from '@/components/select';

export default {
  name: 'house',
  components: { DicSelect },
  // 接受父组件的值
  props: {
    changeValue: undefined,
    projectId: undefined,
    operation: undefined,
  },
  data() {
    let validateBorrow = (rule,value,callback) => {
      let val = this.formData3.powerAttrList[0].borrowerOrgType;
      if(!val) {
        callback('请选择一押借款机构')
      }else{
        callback();
      }
    }
    let validateLoneType = (rule,value,callback) => {
      let val = this.formData3.powerAttrList[0].loanType;
      if(!val) {
        callback('请选择一押借款类型')
      }else{
        callback();
      }
    }
    return {
      pickerOption: {
        disabledDate(current) {
          return current && current.getTime() > new Date().getTime();
        },
      },
      activeNames:"0",
      num:1,
      active: 0,
      defaultChangeValue: this.changeValue,
      appointNextTime: undefined,
      updateParam: undefined,
      pledgeType: undefined,
      list: undefined,
      total: 0,
      listLoading: true,
      stepType: undefined,
      defaultProjectId: undefined,
      showError: false,
      regionList: [],
      listQuery: {
        page: 1,
        limit: 20,
        pid: undefined,
        categoryName: undefined,
        sort: 'add_time',
        order: 'desc',
      },
      dataForm: {
        houseList: [

        ]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      data: [{}],
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      textMap: {
        update: '编辑',
        create: '创建',
      },
      rules: {
        name: [{ required: true, message: '姓名', trigger: 'blur' }],
      },
      downloadLoading: false,
      formData3: {

      },
      borrowRules: {
        required: true, validator: validateBorrow, trigger:'change'
      },
      borrowLoneType: {
        required: true, validator: validateLoneType, trigger:'change'
      },
    };
  },
  watch: {
    changeValue: function(val) {
      this.defaultChangeValue = val;
    },
  },
  computed: {},
  created() {
    console.log(this.defaultChangeValue);
    var form = localStorage.getItem('house');
    if (form != undefined) {
      this.dataForm = JSON.parse(form);
      if (this.dataForm.houseHistries != undefined) {
        this.formData3.powerAttrList = this.dataForm.houseHistries;
      }
    }
    var localProjectId = localStorage.getItem('projectId');
    var localPledgeType = localStorage.getItem('pledgeType');
    this.pledgeType = localPledgeType;
    //回填
    if (localProjectId != 'undefined') {
      console.log('回填');
      this.defaultProjectId = localProjectId;
      this.findByProjectId();
    }

    //编辑
    if (this.projectId != undefined) {
      console.log('编辑');
      this.defaultProjectId = this.projectId;
      this.findByProjectId();
      this.defaultChangeValue = 'detail';
    }

    this.getRegionList();
  },
  methods: {
    findByProjectId() {
      this.listLoading = true;
      findByProjectId({ projectId: this.defaultProjectId })
        .then(response => {
          if (response.data != undefined && response.data.length>0) {
            this.dataForm.houseList = response.data;
            //遍历处理多个房产渲染数据
            this.dataForm.houseList.forEach((item,index)=>{

            item.regionValues = [];
            
            item.title = "房产信息栏"+(index+1)
            item.num = index
            if (item.houseHistries != undefined) {
              var hdata = item.houseHistries;
              for (let i = 0; i < hdata.length; i++) {
                (hdata[i].borrowerTypeName = this.getValue(i + 1) + '押借款机构'),
                  (hdata[i].borrowerOrg = hdata[i].borrowerOrg ? Number(hdata[i].borrowerOrg) : undefined);
                  hdata[i].loanType = hdata[i].loanType ? hdata[i].loanType:undefined;
                  hdata[i].borrowerOrgType = hdata[i].borrowerOrgType?hdata[i].borrowerOrgType:undefined;
                  hdata[i].borrowerOrgTypeName = hdata[i].borrowerOrgTypeName?hdata[i].borrowerOrgTypeName:undefined;
              }
              item.houseHistries = hdata;
            }
            item.regionValues.push(item.provinceId);
            item.regionValues.push(item.cityId);
            item.regionValues.push(item.areaId);

            })
            console.log(this.dataForm);
            localStorage.setItem('requestMethod', 'edit');
          } else {
            this.addRow()
          }
        })
        .catch((e) => {
           console.log(e)
        });
    },
    getRegionList() {
      listRegion()
        .then(response => {
          if (response.data != undefined) {
            this.regionList = response.data;
          }
        })
        .catch(() => {});
    },
    addRow(){
      this.dataForm.houseList.push(
        {
        purpose: undefined,
        ownedSituation: undefined,
        accessType: undefined,
        houseAddress: undefined,
        villageName: undefined,
        buildNo: undefined,
        unitNumber: undefined,
        doorNo: undefined,
        currentSituation: undefined,
        houseAge: undefined,
        landNature: undefined,
        houseUse: undefined,
        landUse: undefined,
        durationLandUse: undefined,
        areaTotal: undefined,
        floors: undefined,
        floorsTotal: undefined,
        licenseNo: undefined,
        buildingHead: undefined,
        houseType: undefined,
        projectId: undefined,
        provinceId: undefined,
        cityId: undefined,
        areaId: undefined,
        estateType: undefined,
        licenseTime: undefined,
        houseNature:undefined,
        nowUsage:undefined,
        regionValues:[],
        showTips: false,
        showMessage: undefined,
        title:"房产信息栏"+(this.dataForm.houseList.length+1),
        num: (this.dataForm.houseList.length+1)+"",
        houseHistries: [
          {
            borrowerOrg: undefined,
            borrowerOrgType:undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 1,
            borrowerTypeName: '一押借款机构',
            loanType: undefined,
          },
          {
            borrowerOrg: undefined,
            borrowerOrgType:undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 2,
            borrowerTypeName: '二押借款机构',
            loanType: undefined,
          },
          {
            borrowerOrg: undefined,
            borrowerOrgType:undefined,
            money: undefined,
            deadline: undefined,
            remainCapital: undefined,
            repayWay: undefined,
            borroweType: 3,
            borrowerTypeName: '三押借款机构',
            loanType: undefined,
          },
        ],
      })
       this.dataForm.houseList.forEach((item,index)=>{
                item.title = "房产信息栏"+(index+1)
                item.num = (index+1)+""
            })
    this.activeNames = this.dataForm.houseList.length+""
    },
     // 删除属性列
    removeRow(index) {
      let houseForm = this.dataForm.houseList[index]
      console.log(houseForm)
      deleteHouse({id:houseForm.id})
        .then(response => {
            this.$notify.success("删除成功")
            this.dataForm.houseList.splice(index, 1);
            this.dataForm.houseList.forEach((item,index)=>{
                item.title = "房产信息栏"+(index+1)
            })
        })
        .catch(() => {
          this.$notify.error("删除失败")
        })
      
    },
    handleSeachNumber() {
      if (this.dataForm.unitNumber === undefined) {
        this.showError = false;
        return false;
      }
      findUnitNumber({ unitNumber: this.dataForm.unitNumber })
        .then(response => {
          if (response.data != undefined) {
            if (response.data == 1) {
              this.showError = true;
            } else {
              this.showError = false;
            }
          }
        })
        .catch(() => {});
    },
    rejectLook() {
      this.$router.push('/task/rejectList');
    },
    handleChangeRegion(index) {
      console.log(index);
      let val = this.dataForm.houseList[index].regionValues
      if (val == undefined || val.length == 0) {
        this.dataForm.houseList[index].provinceId = '';
        this.dataForm.houseList[index].cityId = '';
        this.dataForm.houseList[index].areaId = '';
        return false;
      }
      console.log(val,index)
      this.dataForm.houseList[index].provinceId = val[0];
      this.dataForm.houseList[index].cityId = val[1];
      this.dataForm.houseList[index].areaId = val[2];
      detailByAreaId({ areaId: val.lastItem })
        .then(response => {
          let areaName = response.data;
          if ('松江区' === areaName || '青浦区' === areaName) {
            this.dataForm.houseList[index].showTips = true;
            this.dataForm.houseList[index].showMessage = '只做一押';
            return false;
          }
          if ('金山区' === areaName || '奉贤区' === areaName || '崇明县' === areaName) {
            this.dataForm.houseList[index].showTips = true;
            this.dataForm.houseList[index].showMessage = '不符合产品大纲';
            return false;
          }
          this.dataForm.houseList[index].showTips = false;
          this.dataForm.houseList[index].showMessage = undefined;
        })
        .catch(() => {});
    },
    getValue(val) {
      if (val === 1) {
        return '一';
      }
      if (val == 2) {
        return '二';
      }
      if (val == 3) {
        return '三';
      }
    },
    resetForm() {
      this.dataForm = {
      }
    },
    backStep() {
      this.$emit('stepChanged', 3);
    },
    createData(val) {
      console.log(this.projectId);
      this.stepType = val;
      this.dataForm.houseList.forEach((item,index)=>{
        item.projectId = this.defaultProjectId;
      })
      console.log(this.dataForm);
      // localStorage.setItem("house",JSON.stringify(this.dataForm))
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['formData3'].validate((valids,obj) => {
            console.log(obj,'obj')
           if (valids) {
              console.log(this.defaultProjectId);
              var requestMethod = localStorage.getItem('requestMethod');
              if (this.operation === 'add') {
                this.createHouse();
              } else {
                this.updateHouse();
              }
           }
          });
        }
      });
    },
    createHouse() {
      createHouse(this.dataForm.houseList)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '保存成功',
          });
          if (this.defaultChangeValue != 'detail') {
            this.$emit('stepChanged', this.stepType === 1 ? 3 : 5);
          }else{
            this.$emit('getCapital')
          }
        })
        .catch(response => {});
    },
    createHouseDraft(val) {
      this.stepType = val;
      this.dataForm.houseList.forEach((item,index)=>{
        item.houseHistries = this.formData3.powerAttrList;
        item.projectId = this.defaultProjectId;
      })
      createHouseDraft(this.dataForm.houseList)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '草稿保存成功',
          });
          if (val === 2) {
            this.$router.push('/project/index');
          } else {
            if (this.defaultChangeValue != 'detail') {
              this.$emit('stepChanged', this.stepType === 1 ? 3 : 5);
            }else{
              this.$emit('getCapital')
            }
          }
        })
        .catch(response => {});
    },
    updateHouse() {
      updateHouse(this.dataForm.houseList)
        .then(response => {
          this.$notify.success({
            title: '成功',
            message: '保存成功',
          });
          if (this.defaultChangeValue != 'detail') {
            this.$emit('stepChanged', this.stepType === 1 ? 3 : 5);
            
          }else{
            this.$emit('getCapital')
          }
        })
        .catch(response => {});
    },
    borrowTypeChange(value,item) {
      item.borrowerOrgType = value;
    },
    loneTypeChange(value,item,index) {
      item.loanType = value;
    },
    vailInput(type){
      var reg = /[\(]/g,reg2 = /[\)]/g,reg3 = /\s*/g;
      this.dataForm[type] = this.dataForm[type].toUpperCase();
      this.dataForm[type] = this.dataForm[type].replace(reg,"（").replace(reg2,"）").replace(reg3,"");
    }
  },
};
</script>
<style scoped>
.parentColl >>> .el-collapse-item__header{
  min-height: 95px;
  font-size: 20px;
  font-weight: 1000;
  padding:20px;
}

</style>
<style>
  .house .el-form--inline .el-form-item{
    width: 24%;
  }
  .house  .el-input-group__append, .house  .el-input-group__prepend{
    padding: 0 10px;
  }
</style>